package com.dongnam.quanly.web.nghiepvu.khohang.tonkho;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.TonKhoController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.NganHang;
import com.dongnam.quanly.common.model.PhieuNhapXuat;
import com.dongnam.quanly.common.model.TonKho;
import com.dongnam.quanly.common.model.enumtype.LoaiPhieu;
import com.dongnam.quanly.common.model.enumtype.TrangThaiTonKho;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.danhmuc.nganhang.NganHangModel;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "TonKhoBean")
@SessionScoped
public class TonKhoBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(TonKhoBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private TonKhoModel tonKhoModel;

	// for add TonKho
	private TonKho tonKho;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for load danh sach phong ban
	private TonKhoController tonKhoController;

	// for edit phongBan
	private TonKho selectedTonKho;
	private List<TonKho> listTonKho;

	public TonKhoBean() {
		super();
		tonKho = new TonKho();
		loadTonKho();
		// TODO Auto-generated constructor stub
	}

	public TonKhoController gettonKhoController() {

		if (tonKhoController == null)
			tonKhoController = new TonKhoController();
		return tonKhoController;
	}

	public void settonKhoController(TonKhoController tonKhoController) {
		this.tonKhoController = tonKhoController;
	}

	public void downloadFileCSV() {

		File excelfile = new File("TON_KHO.xls");
		List<TonKho> list = gettonKhoController().findAll("orderNumber", "DESCENDING");
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);

			sheet.addCell(new Label(1, 0, "Kho Hàng", titleformat));
			sheet.addCell(new Label(2, 0, "Vật Tư Hàng Hóa", titleformat));
			sheet.addCell(new Label(3, 0, "SerialNumber", titleformat));
			sheet.addCell(new Label(4, 0, "ProductName", titleformat));
			sheet.addCell(new Label(5, 0, "Giá Sản phẩm", titleformat));
			sheet.addCell(new Label(6, 0, "Diễn giải", titleformat));
			sheet.addCell(new Label(7, 0, "Phiếu Nhập Kho", titleformat));
			sheet.addCell(new Label(8, 0, "Phiếu Xuất Kho", titleformat));
			sheet.addCell(new Label(9, 0, "Trạng thái", titleformat));

			for (int i = 0; i < length; i++) {
				sheet.addCell(new Label(1, i + 1, list.get(i).getKhoHang(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getVatTuHangHoa(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getSerialNumber(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getProductName(), contentformat));
				sheet.addCell(new Label(5, i + 1, String.valueOf(list.get(i).getGiaSanPham()), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getDienGiai(), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getPhieuNhapKho(), contentformat));
				sheet.addCell(new Label(8, i + 1, list.get(i).getPhieuXuatKho(), contentformat));
				sheet.addCell(new Label(9, i + 1, list.get(i).getTrangThai().name(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "TON_KHO.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void resetFormAdd() {
		tonKho = new TonKho();
	}

	public void notifyAdd() {
		isEdit = false;
		resetFormAdd();
	}

	public void notifyEdit(TonKho tonKho) {
		isEdit = true;
		this.selectedTonKho = tonKho;
		this.tonKho.fillTonKho(tonKho);
		// loadTonKho();
		this.listTonKho = gettonKhoController().findAll("orderNumber", "DESCENDING");

	}

	public void removeTonKho() {

		if (this.selectedTonKho != null) {
			gettonKhoController().makeTransient(this.selectedTonKho);
			loadTonKho();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {

			logger.debug("Edit new TonKho");

			if (this.selectedTonKho != null) {

				gettonKhoController().makePersistent(this.tonKho);
				// change state of parent
				context.addCallbackParam("opSuccess", true);
			}

		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadTonKho();

	}

	public TrangThaiTonKho[] getListTrangThaiTonKho() {
		return TrangThaiTonKho.values();
	}

	public void loadTonKho() {
		if (listTonKho == null) {
			listTonKho = new ArrayList<TonKho>();
		}

		listTonKho = gettonKhoController().findAll("orderNumber", "DESCENDING");
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadTonKho();
		WebUtil.redirect("/pages/nghiepvu/kho/tonKho.xhtml");
	}

	public TonKhoModel gettonKhoModel() {
		return tonKhoModel;
	}

	public void settonKhoModel(TonKhoModel tonKhoModel) {
		this.tonKhoModel = tonKhoModel;
	}

	public TonKho gettonKho() {
		return tonKho;
	}

	public void settonKho(TonKho tonKho) {
		this.tonKho = tonKho;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public TonKhoModel getTonKhoModel() {
		return tonKhoModel;
	}

	public void setTonKhoModel(TonKhoModel tonKhoModel) {
		this.tonKhoModel = tonKhoModel;
	}

	public TonKho getTonKho() {
		return tonKho;
	}

	public void setTonKho(TonKho tonKho) {
		this.tonKho = tonKho;
	}

	public TonKho getSelectedTonKho() {
		return selectedTonKho;
	}

	public void setSelectedTonKho(TonKho selectedTonKho) {
		this.selectedTonKho = selectedTonKho;
	}

	public TonKhoController getTonKhoController() {
		return tonKhoController;
	}

	public void setTonKhoController(TonKhoController tonKhoController) {
		this.tonKhoController = tonKhoController;
	}

	public List<TonKho> getListTonKho() {
		return listTonKho;
	}

	public void setListTonKho(List<TonKho> listTonKho) {
		this.listTonKho = listTonKho;
	}

}
